
package com.quyang.voice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quyang.voice.dao.*;
import com.quyang.voice.model.*;
import com.quyang.voice.model.vo.MissuUsersBaseVo;
import com.quyang.voice.model.vo.PublishsListVo;
import com.quyang.voice.model.vo.UsersVo;
import com.quyang.voice.service.IMissuUsersService;
import com.quyang.voice.service.IUserService;
import com.quyang.voice.token.SecurityUtils;
import com.quyang.voice.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    IUserService userService;

    @Autowired
    PublishsMapper publishsMapper;

//    @Autowired
//    IUserManage userManage;

    @Autowired
    UsersMapper userMapper;


    @Autowired
    IMissuUsersService missuUsersService;



    @Autowired
    ReportMapper reportMapper;

    @Autowired
    PublishsLikeMapper publishsLikeMapper;

    @Autowired
    StorageMapper storageMapper;

    @Autowired
    BurnAfterReadingDao burnAfterReadingDao;


    @Autowired
    UserBlackMapper userBlackMapper;

    @Autowired
    DynamicDao dynamicDao;


    @Override
    public ResponseUtil<UsersVo> getUsersById(Long userId,Long toUserId){
        try {
            UsersVo obj=userMapper.getUserBase(toUserId);
            Users user1=userMapper.selectByUserId(userId);
            Users user2=userMapper.selectByUserId(toUserId);
            if (null != obj ) {
                obj.setIsMe(userId==toUserId);

                if (userId==toUserId){
                    obj.setDistance("0");
                }else {
                    if (user1.getLoginLat()!=null&&StringUtils.isNotBlank(user1.getLoginLat()) &&user2.getLoginLat()!=null&& StringUtils.isNotBlank(user2.getLoginLat())){
                        obj.setDistance(SafeUtils.getDistance(Double.parseDouble(user1.getLoginLot()),Double.parseDouble(user1.getLoginLat()),
                                Double.parseDouble(user2.getLoginLot()),Double.parseDouble(user2.getLoginLat())));
                    }
                }

//                obj.setIsFollow(followsMappingMapper.selectCount(new QueryWrapper<FollowsMapping>().eq("user_id",userId).eq("follow_user_id",toUserId))>0);
//                obj.setIsVerify(user2.getIdCard()!=null);
                //作品集合
                List<PublishsListVo> aaa = publishsMapper.getMyPublishList1(toUserId);
                obj.setPublishs(aaa);
                obj.setCity(user2.getCity());
                obj.setIsBlack(userBlackMapper.selectCount(new QueryWrapper<UserBlack>().eq("user_id",userId).eq("black_id",toUserId))>0);
                return ResponseUtil.suc(obj);
            }else {
                return ResponseUtil.fail(ResultCode.FAIL);
            }
        }catch (Exception e){
            logger.error("UsersServiceImpl.getUsersById", e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR);
        }
    }

    @Override
    public ReturnJson updateUsers(Users user){
        try {
            if (null != user) {
                boolean rsg = userService.updateById(user);
                if (rsg) {
                    return ReturnJson.suc(ResultCode.SUCCESS);
                }else {
                    return ReturnJson.fail(ResultCode.FAIL);
                }
            }else {
                return ReturnJson.fail(ResultCode.PARAM_IS_INVALID);
            }
        } catch (Exception e) {
            logger.error("UsersServiceImpl.updateUsers", e);
            return ReturnJson.fail(ResultCode.SYSTEM_ERROR);
        }
    }

    @Override
    public ReturnJson updateUserWx(Long userId, String phone, String vCode, String openId) {

        return ReturnJson.fail(ResultCode.SYSTEM_ERROR);
    }

    @Override
    public ReturnJson removeUserWx(Long userId, String phone, String vCode) {

        return ReturnJson.fail(ResultCode.SYSTEM_ERROR);
    }

    @Override
    public ReturnJson updPwd(Long id, String oldPwd, String newPwd) {

        return ReturnJson.fail(ResultCode.SYSTEM_ERROR);
    }

    @Override
    public ReturnJson changePhone(Long id, String phone, String vCode) {

        return ReturnJson.fail(ResultCode.SYSTEM_ERROR);
    }

    @Override
    public ResponseUtil<IPage<Users>> getUsersPages(Integer pageNum,Integer pageSize){
        try {
            Page<Users> page=new Page<Users>(pageNum,pageSize);
            QueryWrapper<Users> queryWrapper =new QueryWrapper<Users>();
            //分页数据
            IPage<Users> pageData=userService.page(page, queryWrapper);
            return ResponseUtil.suc(pageData);
        } catch (Exception e) {
            logger.error("UsersServiceImpl.getUsersPages", e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR);
        }
    }

    //首页搜索用户
//    @Override
//    public ResponseUtil<PageInfo<IndexSearchUsersVo>> searchUser(Integer pageNum, Integer pageSize ,Long userId, String userName) {
//        try {
//            PageHelper.startPage(pageNum,pageSize);
//            List<IndexSearchUsersVo> usersVoList = userMapper.searchUser(userId,userName);//搜索到的用户列表
//            for (IndexSearchUsersVo usersVo:usersVoList) {
//                FollowsMapping followsMapping = followsMappingMapper.selectOne(new QueryWrapper<FollowsMapping>()
//                        .eq("user_id",userId).eq("follow_user_id",usersVo.getId()));
//                if(null!=followsMapping){
//                    usersVo.setFollow(1);
//                }else{
//                    usersVo.setFollow(0);
//                }
//            }
//            if(usersVoList.size()>0){
//                PageInfo<IndexSearchUsersVo> pageInfo = new PageInfo<IndexSearchUsersVo>(usersVoList);
//                return ResponseUtil.suc(pageInfo);
//            }else{
//                return ResponseUtil.suc();
//            }
//        } catch (Exception e) {
//            logger.error("UsersServiceImpl.searchUser", e);
//            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR);
//        }
//    }

    @Override
    public ReturnJson forgetPwd(String phone, String newPwd, String vCode) {
        return null;
    }

    @Override
    public ReturnJson inviteUser(Long id, String inviteCode) {
        return null;
    }

    @Override
    public ReturnJson blackUser(Integer userId,Integer blackUserId,Integer type) {
        try {
            int result = 0;
            if(type==0){//取消拉黑
                result = userBlackMapper.delete(new QueryWrapper<UserBlack>()
                        .eq("user_id",userId).eq("black_id",blackUserId));
            }else if (type==1){//拉黑
                UserBlack userBlacked = userBlackMapper.selectOne
                        (new QueryWrapper<UserBlack>().eq("user_id",userId).eq("black_id",blackUserId));
                if(null!=userBlacked){
                    return ReturnJson.fail(ResultCode.REPEAT_ERROR);
                }
                UserBlack userBlack = new UserBlack();
                userBlack.setUserId(userId);
                userBlack.setBlackId(blackUserId);
                userBlack.setCreateTime(new Date());
                result = userBlackMapper.insert(userBlack);
            }
            if(result>0){
                return ReturnJson.suc(ResultCode.SUCCESS);
            }else{
                return ReturnJson.fail(ResultCode.FAIL);
            }
        } catch (Exception e) {
            logger.error("UsersServiceImpl.blackUser", e);
            return ReturnJson.fail(ResultCode.SYSTEM_ERROR);
        }
    }

    @Override
    public ResponseUtil blackUserDetail(Integer userId,Integer blackUserId) {
        try {
            int result = 0;

                UserBlack userBlacked = userBlackMapper.selectOne
                        (new QueryWrapper<UserBlack>().eq("user_id",userId).eq("black_id",blackUserId));
                if (userBlacked == null){
                    return ResponseUtil.suc(0);
                }else {
                    return ResponseUtil.suc(1);
                }


        } catch (Exception e) {
            logger.error("UsersServiceImpl.blackUser", e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR);
        }
    }

    @Override
    public ResponseUtil<List<MissuUsersBaseVo>> getMyBlackUser(Integer userId) {
        try {



            List<UserBlack> blackList = userBlackMapper.selectList
                    (new QueryWrapper<UserBlack>().eq("user_id",userId));
            if(blackList.size()>0){
                List<MissuUsersBaseVo> voList = new ArrayList<MissuUsersBaseVo>();
                for (UserBlack userBlack:blackList) {
                    MissuUsersBaseVo userBase = missuUsersService.getUserBase(userBlack.getBlackId());
                    if(null!=userBase){
                        voList.add(userBase);
                    }
                }
                return ResponseUtil.suc(voList);
            }else{
                return ResponseUtil.suc();
            }
        } catch (Exception e) {
            logger.error("UsersServiceImpl.getMyBlackUser", e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR);
        }
    }



    @Override
    public ResponseUtil<List<MissuUsersBaseVo>> getBlackUser(Integer userId) {
        try {

            List<UserBlack> blackList = userBlackMapper.selectList
                    (new QueryWrapper<UserBlack>().eq("black_id",userId));
            if(blackList.size()>0){
                List<MissuUsersBaseVo> voList = new ArrayList<MissuUsersBaseVo>();
                for (UserBlack userBlack:blackList) {
                    MissuUsersBaseVo userBase = missuUsersService.getUserBase(userBlack.getUserId());
                    if(null!=userBase){
                        voList.add(userBase);
                    }
                }
                return ResponseUtil.suc(voList);
            }else{
                return ResponseUtil.suc();
            }
        } catch (Exception e) {
            logger.error("UsersServiceImpl.getMyBlackUser", e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR);
        }
    }

    @Override
    public ReturnJson burnAfterReadingUser(Integer userId, Integer blackUserId, Integer time) {
        try {
            int result = 0;
            BurnAfterReadingExample burnAfterReadingExample = new BurnAfterReadingExample();
            burnAfterReadingExample.createCriteria().andUserIdEqualTo(userId).andReadUserIdEqualTo(blackUserId);
            List<BurnAfterReading> burnAfterReadings = burnAfterReadingDao.selectByExample(burnAfterReadingExample);


            if(burnAfterReadings.size()>0){
                BurnAfterReading burnAfterReading = burnAfterReadings.get(0);
                burnAfterReading.setTime(time);
                burnAfterReadingDao.updateByExample(burnAfterReading,burnAfterReadingExample);

            }else {
                BurnAfterReading burnAfterReading = new BurnAfterReading();
                burnAfterReading.setUserId(userId);
                burnAfterReading.setReadUserId(blackUserId);
                burnAfterReading.setCreateTime(new Date());
                burnAfterReading.setTime(time);
                burnAfterReadingDao.insert(burnAfterReading);
            }




//
//            if(type==0){//取消拉黑
//                burnAfterReadingDao.deleteByExample(burnAfterReadingExample);
////                result = burnAfterReadingDao.delete(new QueryWrapper<UserBlack>()
////                        .eq("user_id",userId).eq("black_id",blackUserId));
//            }else if (type==1){//拉黑
//
//                List<BurnAfterReading> burnAfterReadings = burnAfterReadingDao.selectByExample(burnAfterReadingExample);
//
//                if(burnAfterReadings.size()>0){
//                    return ReturnJson.fail(ResultCode.REPEAT_ERROR);
//                }
//                BurnAfterReading burnAfterReading = new BurnAfterReading();
//
////                UserBlack userBlack = new UserBlack();
//                burnAfterReading.setUserId(userId);
//                burnAfterReading.setReadUserId(blackUserId);
//                burnAfterReading.setCreateTime(new Date());
//                result = burnAfterReadingDao.insert(burnAfterReading);
//            }
//            if(result>0){
//                return ReturnJson.suc(ResultCode.SUCCESS);
//            }else{
//                return ReturnJson.fail(ResultCode.FAIL);
//            }
            return ReturnJson.suc(ResultCode.SUCCESS);
        } catch (Exception e) {
            logger.error("UsersServiceImpl.blackUser", e);
            return ReturnJson.fail(ResultCode.SYSTEM_ERROR);
        }
    }

    @Override
    public ResponseUtil burnAfterReadingUserDetail(Integer userId, Integer blackUserId) {
        try {

            BurnAfterReadingExample burnAfterReadingExample = new BurnAfterReadingExample();
            burnAfterReadingExample.createCriteria().andUserIdEqualTo(userId).andReadUserIdEqualTo(blackUserId);
            List<BurnAfterReading> burnAfterReadings = burnAfterReadingDao.selectByExample(burnAfterReadingExample);
            if (burnAfterReadings.size() == 0){
                return ResponseUtil.suc(0);
            }else {
                return ResponseUtil.suc(1);
            }


        } catch (Exception e) {
            logger.error("UsersServiceImpl.blackUser", e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR);
        }
    }

    @Override
    public ResponseUtil<List<MissuUsersBaseVo>> getMyBurnAfterReadingUser(Integer userId,Integer burnAfterReadingId) {
        try {
            BurnAfterReadingExample burnAfterReadingExample = new BurnAfterReadingExample();
            burnAfterReadingExample.createCriteria().andUserIdEqualTo(userId).andReadUserIdEqualTo(burnAfterReadingId);
            List<BurnAfterReading> burnAfterReadings = burnAfterReadingDao.selectByExample(burnAfterReadingExample);


//            List<UserBlack> blackList = userBlackMapper.selectList
//                    (new QueryWrapper<UserBlack>().eq("user_id",userId));
            if(burnAfterReadings.size()>0){
                List<MissuUsersBaseVo> voList = new ArrayList<MissuUsersBaseVo>();
                for (BurnAfterReading burnAfterReading:burnAfterReadings) {
                    MissuUsersBaseVo userBase = missuUsersService.getUserBase(burnAfterReading.getReadUserId());
                    userBase.setTime(burnAfterReading.getTime());
                    if(null!=userBase){
                        voList.add(userBase);
                    }
                }
                return ResponseUtil.suc(voList);
            }else{
                return ResponseUtil.suc();
            }
        } catch (Exception e) {
            logger.error("UsersServiceImpl.getMyBlackUser", e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR);
        }
    }

    @Override
    public ResponseUtil<List<MissuUsersBaseVo>> getBurnAfterReadingUser(Integer userId, Integer burnAfterReadingId) {
        try {
            BurnAfterReadingExample burnAfterReadingExample = new BurnAfterReadingExample();
            burnAfterReadingExample.createCriteria().andReadUserIdEqualTo(userId).andUserIdEqualTo(burnAfterReadingId);
            List<BurnAfterReading> burnAfterReadings = burnAfterReadingDao.selectByExample(burnAfterReadingExample);

            if(burnAfterReadings.size()>0){
                List<MissuUsersBaseVo> voList = new ArrayList<MissuUsersBaseVo>();
                for (BurnAfterReading burnAfterReading:burnAfterReadings) {
                    MissuUsersBaseVo userBase = missuUsersService.getUserBase(burnAfterReading.getUserId());
                    userBase.setTime(burnAfterReading.getTime());
                    if(null!=userBase){
                        voList.add(userBase);
                    }
                }
                return ResponseUtil.suc(voList);
            }else{
                return ResponseUtil.suc();
            }
        } catch (Exception e) {
            logger.error("UsersServiceImpl.getMyBlackUser", e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR);
        }
    }


    @Override
    public ReturnJson dynamic(Integer userId,String blackUserId,Integer type ,Integer dynamicType) {

        String[] split = blackUserId.split(",");
        int results = 0;
        for (String str: split
             ) {

            try {
                int result = 0;
                DynamicExample dynamicExample = new DynamicExample();
                dynamicExample.createCriteria().andUserIdEqualTo(userId).andBlackIdEqualTo(Integer.valueOf(str)).andTypeEqualTo(dynamicType);
                if(type==0){//取消拉黑
                    result = dynamicDao.deleteByExample(dynamicExample);
                }else if (type==1){//拉黑
//                DynamicExample dynamicExample = new DynamicExample();

                    List<Dynamic> dynamics = dynamicDao.selectByExample(dynamicExample);
                    System.out.println(dynamics);
//                UserBlack userBlacked = userBlackMapper.selectOne
//                        (new QueryWrapper<UserBlack>().eq("user_id",userId).eq("black_id",blackUserId));
                    if(dynamics.size() > 0){
                        return ReturnJson.fail(ResultCode.REPEAT_ERROR);
                    }
                    Dynamic dynamic = new Dynamic();
                    dynamic.setUserId(userId);
                    dynamic.setBlackId(Integer.valueOf(str));
                    dynamic.setCreateTime(new Date());
                    dynamic.setType(dynamicType);
                    result = dynamicDao.insert(dynamic);
                }
                if(result>0){
                    results++;
//                    return ReturnJson.suc(ResultCode.SUCCESS);
                }
            } catch (Exception e) {
                logger.error("UsersServiceImpl.blackUser", e);
                return ReturnJson.fail(ResultCode.SYSTEM_ERROR);
            }

        }
        if(results>0){
            return ReturnJson.suc(ResultCode.SUCCESS);
        }else{
            return ReturnJson.fail(ResultCode.FAIL);
        }

    }

    @Override
    public ResponseUtil dynamicDetail(Integer userId,Integer blackUserId ,Integer dynamicType) {
        try {
            int result = 0;
            DynamicExample dynamicExample = new DynamicExample();
            dynamicExample.createCriteria().andUserIdEqualTo(userId).andBlackIdEqualTo(blackUserId).andTypeEqualTo(dynamicType);
            List<Dynamic> dynamics = dynamicDao.selectByExample(dynamicExample);
//            UserBlack userBlacked = userBlackMapper.selectOne
//                    (new QueryWrapper<UserBlack>().eq("user_id",userId).eq("black_id",blackUserId));
            if (dynamics.size() == 0){
                return ResponseUtil.suc(0);
            }else {
                return ResponseUtil.suc(1);
            }


        } catch (Exception e) {
            logger.error("UsersServiceImpl.blackUser", e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR);
        }
    }

    @Override
    public ResponseUtil<List<MissuUsersBaseVo>> getMyDynamic(Integer userId ,Integer dynamicType) {
        try {

            DynamicExample dynamicExample = new DynamicExample();
            dynamicExample.createCriteria().andUserIdEqualTo(userId).andTypeEqualTo(dynamicType);
            List<Dynamic> dynamics = dynamicDao.selectByExample(dynamicExample);

//            List<UserBlack> blackList = userBlackMapper.selectList
//                    (new QueryWrapper<UserBlack>().eq("user_id",userId));
            if(dynamics.size()>0){
                List<MissuUsersBaseVo> voList = new ArrayList<MissuUsersBaseVo>();
                for (Dynamic dynamic:dynamics) {
                    MissuUsersBaseVo userBase = missuUsersService.getUserBase(dynamic.getBlackId());
                    if(null!=userBase){
                        voList.add(userBase);
                    }
                }
                return ResponseUtil.suc(voList);
            }else{
                return ResponseUtil.suc();
            }
        } catch (Exception e) {
            logger.error("UsersServiceImpl.getMyBlackUser", e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR);
        }
    }



    @Override
    public ResponseUtil<List<MissuUsersBaseVo>> getDynamicUser(Integer userId ,Integer dynamicType) {
        try {
            DynamicExample dynamicExample = new DynamicExample();
            dynamicExample.createCriteria().andBlackIdEqualTo(userId).andTypeEqualTo(dynamicType);
            List<Dynamic> dynamics = dynamicDao.selectByExample(dynamicExample);
//            List<UserBlack> blackList = userBlackMapper.selectList
//                    (new QueryWrapper<UserBlack>().eq("black_id",userId));
            if(dynamics.size()>0){
                List<MissuUsersBaseVo> voList = new ArrayList<MissuUsersBaseVo>();
                for (Dynamic dynamic:dynamics) {
                    MissuUsersBaseVo userBase = missuUsersService.getUserBase(dynamic.getUserId());
                    if(null!=userBase){
                        voList.add(userBase);
                    }
                }
                return ResponseUtil.suc(voList);
            }else{
                return ResponseUtil.suc();
            }
        } catch (Exception e) {
            logger.error("UsersServiceImpl.getMyBlackUser", e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR);
        }
    }



}
